<template>
  <base-modal
    :show.sync="visible"
		:title="title"
		width="528px"
		@close="visible = false">
		<div>
      <biz-remote-select
        class="main-dispatcher-user"
        v-model="value"
        cleared
        :remote-method="fetchEngineer"
        :placeholder="$t('common.base.pleaseSelect')"
        :computed-width-keys="['name']"
      ></biz-remote-select>
		</div>

    <div slot="footer" class="dialog-footer">
      <el-button type="plain-third" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :disabled="pending">{{$t('common.base.confirm')}}</el-button>
    </div>
	</base-modal>
</template>

<script>
import { getEngineerDropDownList, grantIsMain } from '@src/api/serviceProviderApi';
export default {
	name: 'MainDispatcher',
	data() {
		return {
			title: this.$t('common.base.setPrincipal'),
			visible: false,
			value: [],
			tenantProviderId: '', // 服务商租户id
      pending: false,
		};
	},
	methods: {
		openDialog(id) {
			this.value = [];
			this.visible = true;
			this.tenantProviderId = id;
		},
		/*查询工程师*/
		async fetchEngineer(params = {}) {
			try {
				let { keyword, pageNum, pageSize } = params;
				const dataToSend = {
					keyword: keyword,
					pageNum,
					pageSize,
					tenantProviderId: this.tenantProviderId,
				};
				let res = await getEngineerDropDownList(dataToSend);
				if (!(res?.result)) return;
				this.handleTagData(res.result.list);
				return res.result;
			}catch (error) {
				console.error('search dept error', error);
			}
		},
		handleTagData(list) {
			 list.map(item => {
				item.label =  (item && item.engineerName) || '';
				item.value = (item && item.engineerId) || '';
			});
		},
		async submit() {
			if(!this.value || !this.value.length) {
				this.$message.warning({
					message: this.$t('serviceProvider.setMainPrincipal'),
					showClose: true,
					duration: 1500,
				});
			} else {
				try {
					let data = {
						tenantProviderId: this.tenantProviderId,
						engineerId: this.value[0].engineerId
					};
					let res = await grantIsMain(data);
					this.$message({
						type: res.success ? 'success' : 'error',
						message: res.success? this.$t('serviceProvider.setPrincipalSuccess') : this.$t('serviceProvider.setPrincipalFailed'),
					});
					this.visible = false;
					this.$emit('refresh');
				} catch (e) {
					console.error(e);
				}
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.main-dispatcher-user {
  padding: 20px;
}
</style>